﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using DoAnPhatTrienPhanMem.Models;

namespace DoAnPhatTrienPhanMem.Controllers
{
    public class AccountController : BaseController
    {

        //
        // GET: /Account/LogOn
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult DanhMucNguoiDung()
        {
            return View();
        }

        public ActionResult AddOrEdit()
        {
            var ID = Request["ID"];
            if (!String.IsNullOrEmpty(ID)) ViewData["ID"] = ID;
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(FormCollection values)
        {
            var result = new Dictionary<String, Object>();

            try
            {
                var ID = values["ID"];
                var entity = String.IsNullOrEmpty(ID)
                             ? new QLNDNguoiDung()
                             : helper.GetOne<QLNDNguoiDung>(s => s.ID.ToString() == ID);
                if (entity == null)
                {
                    return WarningMessage("Không tồn tại");
                }
                // Load data to entity
                entity = (QLNDNguoiDung)GetDataFromForm(entity, values);
                var canbo = helper.GetOne<ToChucCanBoView>(s => s.MaCB == entity.MaCB);
                if (canbo.ViTri == Constants.Constants.ViTri.TRUONG) entity.QuyenTruyCap = Constants.Constants.RoleDefinition.QUANLY;
                else entity.QuyenTruyCap = Constants.Constants.RoleDefinition.CANBO;
                if (entity.ID == Guid.Empty)
                {
                    #region Insert
                    if (helper.EntityExists<QLNDNguoiDung>(s => s.TenND == entity.TenND))
                    {
                        return WarningMessage("Tên đã tồn tại");
                    }
                    entity.ID = Guid.NewGuid();
                    helper.Insert(entity);
                    #endregion
                }
                else
                {
                    #region Update
                    if (helper.EntityExists<QLNDNguoiDung>(s => s.TenND == entity.TenND && s.ID != entity.ID))
                    {
                        return WarningMessage("Tên đã tồn tại");
                    }
                    helper.Update(entity, s => s.ID.ToString() == ID);
                    #endregion
                }
                result.Add("success", true);
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                return WarningMessage("Lỗi :" + e.Message);
            }
        }

        public QLNDNguoiDung GetByID(string ID)
        {
            var data = new QLNDNguoiDung();
            try
            {
                data = helper.GetOne<QLNDNguoiDung>(s => s.ID.ToString() == ID);
            }
            catch
            {
            }
            return data;
        }

        public QLNDNguoiDung GetByUserName(string Username)
        {
            var data = new QLNDNguoiDung();
            try
            {
                data = helper.GetOne<QLNDNguoiDung>(s => s.TenND == Username);
            }
            catch
            {
            }
            return data;
        }

        public JsonResult GetAllOverView()
        {
            var result = new Dictionary<String, Object>();
            var resultList = helper.GetTable<QLNDNguoiDungOverView>().OrderBy(s => s.TenND).ToList();
            var tochuc = helper.GetTable<ToChucCanBo>().ToList();
            foreach (var user in resultList)
            {
                if (!String.IsNullOrEmpty(user.ThuocBanVien))
                {
                    if (user.ThuocBanVien == "VIEN")
                    {
                        var phong = helper.GetOne<Phong>(s => s.MaPhong == user.MaPhongBan);
                        var vien = helper.GetOne<Vien>(s => s.MaVien == phong.MaVien);
                        user.TenBanVien = vien.TenVien + " - " + phong.TenPhong;
                    }
                    else if (user.ThuocBanVien == "BAN")
                    {
                        var ban = helper.GetOne<BanHanhChinh>(s => s.MaBan == user.MaPhongBan);
                        user.TenBanVien = ban.TenBan;
                    }
                }
            }
            result.Add("data", resultList);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //
        // POST: /Account/LogOn


        //
        // GET: /Account/LogOff


        //
        // GET: /Account/Register


        //
        // POST: /Account/Register


        //
        // GET: /Account/ChangePassword


        //
        // POST: /Account/ChangePassword


        //
        // GET: /Account/ChangePasswordSuccess




        public bool CheckRole(string user, string controller, string action)
        {
            var c = false;
            var roledefinition = Constants.Constants.RoleDefinition.KHACH;
            if (!String.IsNullOrEmpty(user)) roledefinition = helper.GetOne<QLNDNguoiDung>(s => s.TenND == user).QuyenTruyCap;
            var roledassignment = Constants.Constants.Roleassignment.KHACH;
            if (roledefinition == Constants.Constants.RoleDefinition.QUANTRI) roledassignment = Constants.Constants.Roleassignment.QUANTRI;
            if (roledefinition == Constants.Constants.RoleDefinition.QUANLY) roledassignment = Constants.Constants.Roleassignment.QUANLY;
            if (roledefinition == Constants.Constants.RoleDefinition.CANBO) roledassignment = Constants.Constants.Roleassignment.QUANLY;
            var module = controller + action;
            if (roledassignment.ToUpper().Contains(module.ToUpper())) c = true;
            return c;
        }

        public bool CheckRole(string user, string controller, string action, string ID)
        {
            var c = false;
            var roledefinition = Constants.Constants.RoleDefinition.KHACH;
            if (!String.IsNullOrEmpty(user)) roledefinition = helper.GetOne<QLNDNguoiDung>(s => s.TenND == user).QuyenTruyCap;
            var roledassignment = Constants.Constants.Roleassignment.KHACH;
            if (roledefinition == Constants.Constants.RoleDefinition.QUANTRI) roledassignment = Constants.Constants.Roleassignment.QUANTRI;
            if (roledefinition == Constants.Constants.RoleDefinition.QUANLY) roledassignment = Constants.Constants.Roleassignment.QUANLY;
            if (roledefinition == Constants.Constants.RoleDefinition.CANBO) roledassignment = Constants.Constants.Roleassignment.QUANLY;
            var module = controller + action;
            if (roledassignment.Contains(module))
            {
                if (roledefinition == Constants.Constants.RoleDefinition.QUANTRI) return true;
                if (roledefinition == Constants.Constants.RoleDefinition.CANBO)
                {
                    var MaCB = GetByUserName(user).MaCB;
                    var IDcanbo = helper.GetOne<SoYeuCanBo>(s => s.MaCB == MaCB).ID;
                    if (IDcanbo.ToString() == ID) return true;
                }
                else if (roledefinition == Constants.Constants.RoleDefinition.QUANLY)
                {
                    var MaCB = GetByUserName(user).MaCB;
                    var IDcanbo = helper.GetOne<SoYeuCanBo>(s => s.MaCB == MaCB).ID;
                    if (IDcanbo.ToString() == ID) return true;
                    else
                    {
                        var DonVi = helper.GetOne<ToChucCanBo>(s => s.MaCB == MaCB);
                        var IDdonvi = "";
                        if (DonVi.ThuocBanVien == "BAN") IDdonvi = helper.GetOne<BanHanhChinh>(s => s.MaBan == DonVi.MaPhongBan).ID.ToString();
                        else IDdonvi = helper.GetOne<Phong>(s => s.MaPhong == DonVi.MaPhongBan).ID.ToString();
                        if (IDdonvi == ID) return true;
                        if (helper.EntityExists<SoYeuCanBo>(s => s.ID.ToString() == ID))
                        {
                            var Macanbo = helper.GetOne<SoYeuCanBo>(s => s.ID.ToString() == ID).MaCB;
                            if (helper.EntityExists<ToChucCanBo>(s => s.MaCB == Macanbo))
                            {
                                var dv = helper.GetOne<ToChucCanBo>(s => s.MaCB == Macanbo);

                                if (DonVi.ThuocBanVien == dv.ThuocBanVien && DonVi.MaPhongBan == dv.MaPhongBan) return true;
                            }
                        }
                    }
                }
            }

            return c;
        }


        public AccountController(IFormsAuthentication formsAuth)
        {
            this.FormsAuth = formsAuth ?? new FormsAuthenticationService();
        }

        public AccountController() : this(null) { }

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public interface IFormsAuthentication
        {
            void SignIn(string userName, bool createPersistentCookie);
            void SignOut();
        }

        public class FormsAuthenticationService : IFormsAuthentication
        {
            public void SignIn(string userName, bool createPersistentCookie)
            {
                FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
            }
            public void SignOut()
            {
                FormsAuthentication.SignOut();
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Needs to take same parameter type as Controller.Redirect()")]
        public JsonResult Login(string Username)
        {
            IDictionary<String, Object> result = new Dictionary<String, Object>();
            if (helper.EntityExists<QLNDNguoiDung>(s => s.TenND == Username))
            {
                //FormsAuthentication.SetAuthCookie(Username, true);
                FormsAuth.SignIn(Username, true);
                Session[Constants.Constants.SessionName.UserName] = Username;

            }
            else
            {
                return WarningMessage(Constants.Constants.Common.TenTruyCapKhongHoacMatKhauSai);
            }
            result.Add("success", true);
            return Json(result);
        }

        public ActionResult Logout()
        {
            //Session[Constants.Constants.SessionName.UserName] = string.Empty;
            //FormsAuthentication.SignOut();
            Session.Abandon();
            FormsAuth.SignOut();
            return RedirectToAction("HomePage", "Home");
        }

        public ActionResult SwitchUser()
        {
            FormsAuth.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
